﻿using System;
using System.Collections;

namespace TK
{
    public partial class CustomSerializer
    {
        void writeGenericDictionary(CustomSerializerState state, IDictionary o, Type typeKey, Type typeValue)
        {
            var objID = state.writeHeader();
            state.writeInt32(o.Count);
            state.writeTypeName(typeKey);
            state.writeTypeName(typeValue);
            writeSingleTypeCollection(state, o.Keys, typeKey);
            writeSingleTypeCollection(state, o.Values, typeValue);

            state.updateHeader(objID);
        }

        IDictionary readGenericDictionary(CustomSerializerState state, Type expectedType, Type ownerType, string propertyName)
        {
            var header = state.readHeader();
            var count = state.readInt32();

            var storedTypeKey = getTypeByName(state.readTypeName(), state.settings.ClassMap);
            var storedValueType = getTypeByName(state.readTypeName(), state.settings.ClassMap);
            var ga = expectedType.GetGenericArguments();

            var listKeys = Array.CreateInstance(storedTypeKey, count) as IList;
            readSingleTypeCollection(state, listKeys, storedTypeKey, ownerType, propertyName + ".Keys");
            if (storedTypeKey != ga[0]) listKeys = convertList(listKeys, ga[0], ownerType, propertyName);
            
            var listValues = Array.CreateInstance(storedValueType, count) as IList;
            readSingleTypeCollection(state, listValues, storedValueType, ownerType, propertyName + ".Values");
            if (storedValueType != ga[1]) listValues = convertList(listValues, ga[1], ownerType, propertyName);

            var o = createObject(expectedType) as IDictionary;
            for (var i = 0; i < listKeys.Count; i++) o.Add(listKeys[i], listValues[i]);
            return o;
        }
    }
}